<template>
    <Menu></Menu>
    <Banner :bannerH="100" ></Banner>
    <div class="container">
        <div class="main">
            <div class="avatar" >
                <el-avatar 
                @click="visible = true"
                class="avatar-main"
                :size="80" 
                :src="ENV_VITE_APP_URL+(token && avatar ? avatar : webAvatar)"/>
            </div>
            <div class="form-container" :class="screenTypeClass">
                <el-form 
                :model="form" 
                size="large"
                label-position="right"
                label-width="auto"
                :rules="rules"
                ref="formRef">
                    <el-form-item label="用户名" prop="userId">
                        <el-input v-model.trim="form.userId" placeholder="用户名"></el-input>
                    </el-form-item>
                    <el-form-item label="昵称" prop="nickname">
                        <el-input v-model.trim="form.nickname" placeholder="昵称"></el-input>
                    </el-form-item>
                    <el-form-item label="邮箱" prop="eMail">
                        <el-input v-model.trim="form.eMail" readonly placeholder="邮箱">
                            <template #append>
                                <el-button icon="Edit" @click="emailVisible = true"/>
                            </template>
                        </el-input>
                    </el-form-item>
                    <el-form-item label="电话号码" prop="phoneNumber">
                        <el-input v-model.trim="form.phoneNumber" placeholder="当前功能还未实装"></el-input>
                    </el-form-item>
                    <el-form-item label="性别" prop="sex">
                        <el-radio-group  v-model="form.sex">
                            <el-radio v-for="item in sexList" :key="item.value" :value="item.value">{{ item.label }}</el-radio>
                        </el-radio-group>
                    </el-form-item>
                    <el-form-item label="格言" prop="slogan">
                        <el-input v-model.trim="form.slogan" placeholder="总有那么一句话影响着你"></el-input>
                    </el-form-item>
                </el-form>
                <SubmitButton @buttonHandle="submitUserInfo"></SubmitButton>
            </div>
        </div>
    </div>
    <!-- 修改头像 -->
    <UploadAvatar v-model:visible="visible" @handleClick="handleClick"></UploadAvatar>
    <!-- 修改邮箱 -->
    <UpdateEmail v-model:visible="emailVisible" @handleClick="updateForm"></UpdateEmail>
</template>

<script setup>
import { reactive } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';

import Menu from '@/layout/components/menu/index-menu.vue';
import Banner from '@/layout/components/banner/banner.vue';
import UploadAvatar from './components/upload-avatar/upload-avatar.vue';
import UpdateEmail from './components/update-email/update-email.vue';
import SubmitButton from '@/components/animation/submit-button/submit-button.vue';

import { usersApi } from '@/api/system/users/users-api';
import { ENV_VITE_APP_URL } from '@/constants/common-const';
import { throttle } from '@/utils/countdown-util';
import { montageStr } from '@/utils/tools-util';

import { storeToRefs } from 'pinia';
import { useUserStore } from '@/store/system/user';
const { token, avatar } = storeToRefs(useUserStore());
import { websiteStore } from '@/store/system/website';
const { webAvatar, screenType } = storeToRefs(websiteStore());

// ========================= 实列挂载之前调用 =========================
onBeforeMount(async () => {
    await useUserStore().getUserInfo();
    setForm();
})

// ========================= 计算属性 =========================
// 移动端适配
const screenTypeClass = computed(() => {
    return {
        [`form-${screenType.value}`]:true
    }
});

// ========================= 修改头像 =========================
let visible = ref(false);
let { id } = useUserStore();
async function handleClick(file) {
    try {
        let avatarFile = new FormData();
        avatarFile.append('avatar', file);
        avatarFile.append('id', id);
        const res = await usersApi.avatar(avatarFile, {'Content-Type': 'multipart/form-data'});
        if(res.meta.status !== 200) throw new Error(res.meta.msg);
        avatar.value = res.data;
        form.avatar = res.data;
        ElMessage.success('修改成功');
    } catch (e) {
        console.error(e);
        ElMessage.error(e.message);
    };
};

// ========================= 提交用户数据 =========================
const form = reactive({
    id:'',              // 主键
    avatar:'',          // 头像
    userId:'',          // 用户id
    nickname:'',        // 昵称
    eMail:'',           // 邮箱
    phoneNumber:'',     // 电话号码
    sex:0,              // 性别
    slogan:'',          // 格言
    roles:[],           // 角色
    updateAt:'',        // 更新时间
});
// 表单控制
const rules = reactive({
    userId: [
        { required: true, message: '请输入用户名', trigger: 'blur' }
    ],
});
const sexList = reactive([
    { value: 1, label:'男'  },
    { value: 2, label:'女'  },
    { value: 3, label:'保密' }
]);

// 提交用户信息
const formRef = ref(null);
async function submitUserInfo() {
    // if(!throttle()) return;
    formRef.value.validate((valid) => {
        if(valid) {
            ElMessageBox.confirm(
                `确认保存？`,
                '提示',
                {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'info',
                }
            ).then(async () => {
                const res = await usersApi.update(form);
                if(res.meta.status !== 200) throw new Error(res.meta.msg);
                updateForm();
                ElMessage.success('修改成功');
            }).catch((e) => {
                e.message ? 
                ElMessage.warning(e.message) : 
                ElMessage.warning('取消保存') ;
            });
        }
    });
    
};

// 初始化表单
function setForm() {
    for(let key in form) {
        form[key] = useUserStore()[key];
    };
    form.roles = montageStr(useUserStore().roles, 'id');
};

// ========================= 修改邮箱 =========================
let emailVisible = ref(false);
async function updateForm() {
    await useUserStore().getUserInfo();
    setForm();
};
</script>

<style lang="scss" scoped>
    @import '@/theme/public.scss';
    @import "./user.scss";
</style>
